package com.czk.utils;

import com.czk.domain.FileTransferProtocol;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/1 14:38
 */
public class FileUtils {
    public static FileTransferProtocol readFile(String filePath) throws IOException {
        // 读取数据
        File file = new File(filePath);
        // 拿到文件长度
        long length = file.length();
        // 创建数组
        ByteBuffer buffer = ByteBuffer.allocate((int) length);
        // 读入数组中
        FileChannel fileChannel = FileChannel.open(Paths.get(filePath), StandardOpenOption.READ);
        // 读取数组
        fileChannel.read(buffer);
        FileTransferProtocol protocol = new FileTransferProtocol();
        protocol.setSize((int) length);
        protocol.setData(buffer);
        // 设置文件名
        protocol.setFileName(file.getName());
        fileChannel.close();
        return protocol;
    }

    public static void writeFile(String filePath, FileTransferProtocol fileTransferProtocol) throws IOException {
        FileChannel fileChannel = FileChannel.open(Paths.get(filePath),
                StandardOpenOption.READ,
                StandardOpenOption.WRITE,
                StandardOpenOption.CREATE);
        //
        ByteBuffer data = (ByteBuffer) fileTransferProtocol.getData();
        // 切换为可读状态
        data.flip();
        // 写入
        fileChannel.write(data);
        fileChannel.close();
    }
}
